package com.sillyhat.common.utils;

import org.apache.log4j.Logger;

import java.sql.*;

/**
 * Created by ${XUSHIKUAN} on 2017-01-07.
 */
public class DBUtils {

    private static Logger logger = Logger.getLogger(DBUtils.class);


    private static DBUtils instance;

    private String driver,url,username,password;

    public DBUtils(String driver,String url,String username,String password){
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
    }

//    public static DBUtils getInstance(String driver,String url,String username,String password) {
//        if(instance == null){
//            synchronized (DBUtils.class){
//                if(instance == null){
//                    instance = new DBUtils(driver,url,username,password);
//                }
//            }
//        }
//        return instance;
//    }

    public Connection getConnection() { // 获得连接对象的方法
        try {
            Class.forName(driver);
            Connection con = DriverManager.getConnection(url,username , password);
            return con;
        }catch (Exception e){
            logger.error("获得数据库连接出现异常",e);
            return null;
        }
    }

    public static void close(Connection con , PreparedStatement p , ResultSet rs){
        if(con != null){
            try {
                con.close();
            } catch (SQLException e) {
                logger.error("Connection close error",e);
            }
        }
        if(p != null){
            try {
                p.close();
            } catch (SQLException e) {
                logger.error("PreparedStatement close error",e);
            }
        }
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                logger.error("ResultSet close error",e);
            }
        }
    }
}
